package com.hb.gateway.config;

import cn.hutool.core.util.StrUtil;
import com.hb.gateway.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.util.ResultUtil;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关统一异常处理
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @date 2021-03-24
 */
@Slf4j
@Order(-1)
@Configuration
public class GatewayHandler implements ErrorWebExceptionHandler {

    /**
     * 服务未找到返回消息
     */
    private static final String MSG_SERVER_NOT_FOUND = "糟糕，服务未找到，请稍后重试。";

    @NonNull
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, @NonNull Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (exchange.getResponse().isCommitted()) {
            log.warn("handle failed for response is commited");
            return Mono.error(ex);
        }
        // 服务未找到
        if (ex instanceof NotFoundException) {
            log.error("handle failed server not found , errorMsg is [{}], stackInfo is " , MSG_SERVER_NOT_FOUND, ex);
            return ResponseUtil.buildResponse(response, ResultUtil.error(MSG_SERVER_NOT_FOUND));
        }

        // 返回状态异常
        if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            String reason = responseStatusException.getReason();
            String msg = StrUtil.isNotEmpty(reason)? reason: ex.getMessage();
            log.error("handle failed , errorMsg is [{}], stackInfo is " , MSG_SERVER_NOT_FOUND, ex);
            return ResponseUtil.buildResponse(response, ResultUtil.error(msg));
        }

        log.error("handle failed , errorMsg is [{}], stackInfo is " , MSG_SERVER_NOT_FOUND, ex);
        return ResponseUtil.buildResponse(response, ResultUtil.error(MSG_SERVER_NOT_FOUND));
    }

}
